package com.example.smart_city_0829.base;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.example.smart_city_0829.SmartCity;
import com.example.smart_city_0829.retrofit.Api;
import com.example.smart_city_0829.retrofit.RetrofitBuilder;
import com.example.smart_city_0829.utils.Constant;
import com.google.gson.Gson;
import com.youth.banner.loader.ImageLoader;

import java.util.Objects;
import java.util.Stack;

public abstract class BaseActivity extends AppCompatActivity {

    protected final static Stack<BaseActivity> activities = new Stack<>();
    protected Api api = RetrofitBuilder.getApi();
    protected static Gson gson = new Gson();

    protected static SharedPreferences sharedPreferences;
    protected SharedPreferences.Editor editor;

    protected static ProgressDialog progressDialog = null;

    protected ImageLoader imageLoader = new ImageLoader() {
        @Override
        public void displayImage(Context context, Object o, ImageView imageView) {
            Glide.with(context)
                    .load(Constant.BASE_URL2 + o)
                    .transform(new RoundedCorners(8), new RoundedCorners(8))
                    .into(imageView);
        }
    };

    protected Context context;
    protected final int PERMISSION_REQUEST_PICTURE_CODE = 0x5842a;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        activities.add(this);
        setContentView(getLayoutId());

        final ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setTitle(getActionBarTitle());
            supportActionBar.setDisplayHomeAsUpEnabled(true);
        }

        sharedPreferences = SmartCity.getSharedPreferences();
        editor = sharedPreferences.edit();

        initView();
        initData();
        initEvent();

//        Intent intent = new Intent();
//        intent.setAction(Intent.ACTION_PICK);
//        intent.setType("image/*");
//        startActivityForResult(intent,1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1){
            if (data != null && null != data.getData()) {
                Uri uri = data.getData();
                String[] fileColumn = {MediaStore.Images.Media.DATA};
                Cursor query = getContentResolver().query(uri, fileColumn, null, null, null);
                int columnIndex = query.getColumnIndex(fileColumn[0]);
                query.moveToFirst();
                String filePath = query.getString(columnIndex);
                query.close();
                showToastShort(filePath);
            }
        }
    }

    @Override
    protected void onDestroy() {
        activities.remove(this);//不使用pop是因为可能在调用popActivityStack时就已经移除了这个activity引用
        progressDialog = null;//重置加载弹窗，activity引用可能已被销毁
        super.onDestroy();
    }

    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void initEvent();

    protected abstract String getActionBarTitle();

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                activities.lastElement().finish();
                return true;
        }
        return true;
    }

    /**
     * 销毁activity
     * @param backStackCount 想要回退的activity层数
     */
    protected void popActivityStack(int backStackCount) {
        for (int i = 0; i < backStackCount; i++) {
            activities.lastElement().finish();
            activities.pop();
        }
    }

    /**
     * 回退至主页
     */
    protected void backToHomeActivity() {
        popActivityStack(activities.size() - 1);
    }

    /**
     * 显示加载弹窗，不可被取消
     * @param title 标题
     * @param content 内容
     * @param style 进度条样式
     */
    protected void showLoadingDialog(@Nullable String title, @Nullable String content, int style) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(BaseActivity.this);
            progressDialog.setProgressStyle(style);
            progressDialog.setTitle(TextUtils.isEmpty(title) ? "稍等" : title);
            progressDialog.setMessage(TextUtils.isEmpty(content) ? "加载中" : content);
            progressDialog.setCancelable(false);
            progressDialog.create();
        }

        progressDialog.show();
    }

    protected void setTitle(String title) {
        Objects.requireNonNull(getSupportActionBar()).setTitle(title);
    }

    protected void migrateTo(Class<? extends BaseActivity> clazz) {
        startActivity(new Intent(this, clazz));
    }

    protected void showToastShort(String tip) {
        Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
    }

    protected boolean hasStoragePermission(){
        boolean has =  checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        if (!has){
            requestStoragePermission();
            return false;
        }else {
            return true;
        }
    }

    protected void requestStoragePermission(){
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_REQUEST_PICTURE_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_PICTURE_CODE){
            if (grantResults.length > 0){
                onStoragePermissionRequestSuccess();
            }else {
                onStoragePermissionRequestFailure();
            }
        }
    }



    protected void onStoragePermissionRequestSuccess(){
        //TODO
        showToastShort("已获得存储权限");
    }

    protected void onStoragePermissionRequestFailure(){
        //TODO
        showToastShort("您已拒绝存储权限");
    }
}
